package com.echat.api.demo.util;


import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.StringTokenizer;

/**
 * Created by EChat
 * URL相关的工具类
 */
public class URLUtil {

    private static final String chatSet = "utf-8";

    public static String encode(String string) {

        try {
            return URLEncoder.encode(string, chatSet);
        } catch (UnsupportedEncodingException e) {
            return null;
        }
    }

    public static String decode(String string) {

        try {
            return URLDecoder.decode(string, chatSet);
        } catch (UnsupportedEncodingException e) {
            return null;
        }
    }

    /**
     * @param queryString url中请求的参数字符串
     * @param parameter   需要解析的参数名称
     * @return 返回制定的参数的值，如果没有则返回null
     */
    public static String getParameterValue(String queryString, String parameter) {
        if (StringUtil.isEmpty(queryString) || StringUtil.isEmpty(parameter)) {
            return null;
        }
        StringTokenizer st = new StringTokenizer(queryString, "&");
        String tempStr = null;
        while (st.hasMoreTokens()) {
            tempStr = st.nextToken();
            if (tempStr != null && tempStr.indexOf("=") != -1) {
                String[] m = tempStr.split("=");
                if (m != null && m.length == 2) {
                    if (parameter.equals(m[0])) {
                        return m[1];
                    }
                }
            }
        }
        return null;
    }


}
